package cn.jinjimi.app.main.adapter;

import android.content.Context;
import android.support.v4.content.ContextCompat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import cn.jinjimi.base.util.DateUtils;
import cn.jinjimi.app.R;
import cn.jinjimi.app.bean.Constants;
import cn.jinjimi.app.entity.Article;
import cn.jinjimi.app.entity.Attachment;
import cn.jinjimi.app.entity.Category;
import cn.jinjimi.app.store.DatabaseManager;
import cn.jinjimi.app.store.entity.ArticleEntity;
import cn.jinjimi.app.main.adapter.extend.MyBaseAdapter;
import cn.jinjimi.app.main.widget.FrescoImageView.FrescoImageView;
import cn.jinjimi.app.main.widget.MatchTextView;
import cn.jinjimi.app.main.widget.SingleLineElipseTextView;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Tony on 11/24/14.
 * modify by Roy on 15-10-23
 */
public class ArticleSearchAdapter extends MyBaseAdapter<Article> {

    private LayoutInflater layoutInflater;
    private Category category;
    private Context mContext;
    private String matchText;

    public ArticleSearchAdapter(Context context) {
        this.mContext = context;
        this.layoutInflater = LayoutInflater.from(context);
    }

    public void setCategory(Category category) {
        this.category = category;
        notifyDataSetChanged();
    }

    public void setMatchText(String matchText) {
        this.matchText = matchText;
    }

    public String getMatchText() {
        return matchText;
    }

    public void syncLocalData(List<Article> articleList) {
        setItems(mixLocalData(articleList));
    }

    public void addAll(List<Article> articles) {
        addItems(mixLocalData(articles));
    }

    /**
     * 检索所有已读文章, 并标记状态
     *
     * @param articleList
     */
    private List<Article> mixLocalData(List<Article> articleList) {
        if (articleList == null)
            return null;
        List<String> ids = new ArrayList<String>();
        for (Article article : articleList) {
            ids.add(article.getId());
        }

        if (ids.size() == 0)
            return articleList;

        List<ArticleEntity> stored = DatabaseManager.getInstance().getArticleDao().findArticleReadedByIdsLocal(ids);

        if (stored != null) {
            for (Article article : articleList) {
                for (ArticleEntity a : stored) {
                    if (article.getId().equals(a.getId())) {
                        article.setReadStatus(Article.STATUS_USER_HAS_READED);
                    }
                }
            }
        }

        return articleList;
    }

    /**
     * 记录已读过的文章
     *
     * @param article
     */
    public void addReadedArticle(Article article) {
        if (article.getReadStatus() == Article.STATUS_USER_HAS_READED)
            return;

        article.setReadStatus(Article.STATUS_USER_HAS_READED);

        ArticleEntity a = new ArticleEntity();

        a.setId(article.getId());
        a.setTitle(article.getTitle());
        a.setBaseUrl(article.getBase_url());
        a.setAuthor(article.getAuthor());
        a.setAuthorId(article.getAuthor_id());
        a.setReadum(article.getReadNum());
        a.setReadStatus(ArticleEntity.STATUS_USER_HAS_READED);

        //save 2 local db.
        DatabaseManager.getInstance().getArticleDao().insertOrReplace(a);
    }

    /**
     * 将文章item标记为已读
     *
     * @param view
     * @param article
     */
    public void tagAsReaded(View view, Article article) {
        TextView title = (TextView) view.findViewById(R.id.tv_title);
        if (title != null && article != null) {
            title.setTextColor(ContextCompat.getColor(mContext, R.color.listItem_desc_color));
            addReadedArticle(article);
        }
    }

    /**
     * 返回当前item的样式
     */
    public int getItemViewType(int position) {
        Article article = getItem(position);
        return article.getShowStyle();
    }

    /**
     * 返回view样式种类总数
     */
    public int getViewTypeCount() {
        return 3;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        Article article = getItem(position);
        TextDataHolder commonDataHolder;
        if (convertView == null) {
            convertView = layoutInflater.inflate(R.layout.item_article, null);
            commonDataHolder = new TextDataHolder(convertView);
            convertView.setTag(commonDataHolder);
        } else {
            commonDataHolder = (TextDataHolder) convertView.getTag();
        }
        initDataWorld(article, commonDataHolder);

        return convertView;
    }

    class TextDataHolder {
        private MatchTextView tvTitle;
        private SingleLineElipseTextView tvShareInfo;
        private FrescoImageView ivCover;
        private RelativeLayout rlShare;

        public TextDataHolder(View parent) {
            initView(parent);
        }

        private void initView(View itemView) {
            tvTitle = (MatchTextView) itemView.findViewById(R.id.tv_title);
            tvShareInfo = (SingleLineElipseTextView) itemView.findViewById(R.id.tv_share_msg);
            rlShare = (RelativeLayout) itemView.findViewById(R.id.rl_share);
            ivCover = (FrescoImageView) itemView.findViewById(R.id.iv_cover);
            rlShare.setVisibility(View.INVISIBLE);
            tvShareInfo.setTextSize(11);
        }
    }

    /**
     * 填充文字
     *
     * @param holder
     */
    private void initDataWorld(Article article, TextDataHolder holder) {
        holder.tvTitle.setText(article.getTitle(), matchText);
        //根据已读状态显示不同的标题颜色
        holder.tvTitle.setTextColor(ContextCompat.getColor(mContext, article.getReadStatus() == Article.STATUS_USER_HAS_READED ? R.color.listItem_flag_color : R.color.text_black));

        //获取cover
        String coverUrl = null;
        List<Attachment> mAttach = article.getAttachments();
        if (mAttach != null && !mAttach.isEmpty()) {
            for (Attachment attach : mAttach) {
                if (Constants.COVER.equals(attach.getUsage())) {
                    coverUrl = attach.getBase_url() + "172x132";
                    break;
                }
            }
        }
        holder.ivCover.loadView(coverUrl);

        holder.tvShareInfo.setText(DateUtils.dealWithDateInArticle(mContext, article.getPublishAt()),null);
    }

}
